<?php
/**
 * Created by PhpStorm.
 * User: 87393
 * Date: 2019-03-27
 * Time: 11:54
 */

namespace App\Http\Controllers\Admin\View;


use App\Http\Controllers\Controller;
use App\Http\Repositories\Eloquent\Role;
use App\Http\Repositories\Services\IPermission;
use App\Http\Repositories\Services\IRole;
use Illuminate\Http\Request;

class RoleController extends Controller
{

    protected $roleService;
    protected $permissionService;

    public function __construct(
        IRole $roleService,
        IPermission $permissionService
    )
    {
        $this->roleService = $roleService;
        $this->permissionService = $permissionService;
    }

    public function index()
    {
        return view('admin.role.index');
    }

    public function store()
    {
        return view('admin.role.create');
    }

    public function update($id)
    {
        $dao = $this->roleService->byId($id);
        return view('admin.role.edit',compact('dao'));
    }

    public function permission($id)
    {
        $role = Role::findOrFail($id);
        $permissions = $this->permissionService->getTree();
        foreach ($permissions as $key1 => $item1){
            $permissions[$key1]['checked'] = $role->hasPermissionTo($item1['id']) ? 'checked' : false ;
            if (isset($item1['children'])){
                foreach ($item1['children'] as $key2 => $item2){
                    $permissions[$key1]['children'][$key2]['checked'] = $role->hasPermissionTo($item2['id']) ? 'checked' : false ;
                    if (isset($item2['children'])){
                        foreach ($item2['children'] as $key3 => $item3){
                            $permissions[$key1]['children'][$key2]['children'][$key3]['checked'] = $role->hasPermissionTo($item3['id']) ? 'checked' : false ;
                        }
                    }
                }
            }

        }
        return view('admin.role.permission',compact('role','id','permissions'));
    }

    public function assignPermission(Request $request,$id)
    {
        $role = Role::findOrFail($id);
        $permissions = $request->get('permissions');

        if (empty($permissions)){
            $role->permissions()->detach();
            return redirect()->to(route('admin.role'))->with(['status'=>'已更新角色权限']);
        }
        $role->syncPermissions($permissions);
        return redirect()->to(route('admin.role'))->with(['status'=>'已更新角色权限']);
    }

}